﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bricks.MiuiThemeMaker.OrmModel;
using System.IO;

namespace Bricks.MiuiThemeMaker.BRMiuiThemeMaker
{
    /*********************************************************
     * 1.版权：积木工场 Bricks Factory
     * 2.作用：元素BLL（含类型等）
     * 3.创建人：罗泽新
     * 4.创建日期：2012-05-01
     * 5.最后修改人：罗泽新
     * 6.最后修改日期：2012-05-09
     * 7.修改项目：
     * *******************************************************/
    public class ElementBLL
    {
        #region 原设计：作废
        //#region 树构建
        ///// <summary>
        ///// 获取元素树
        ///// </summary>
        ///// <param name="dbType">数据库类型</param>
        ///// <returns></returns>
        //public List<ElementNode> GetElementTree(DBType dbType)
        //{
        //    List<ElementNode> result = new List<ElementNode>();
        //    switch (dbType)
        //    {
        //        case DBType.MsSql: break;
        //        case DBType.SqlCompact:
        //            using (DBEntities dbContext = new DBEntities())
        //            {
        //                var query = from m in dbContext.BF_Element
        //                            orderby m.ParentID, m.OrderNo
        //                            select new ElementNode
        //                            {
        //                                #region 原设计
        //                                //ID = m.ID,
        //                                //Name = m.Name,
        //                                //ParentID = m.ParentID,
        //                                ////NType = m.Type == null ? NodeType.File : (m.Type == 1 ? NodeType.Preview : (m.Type == 2 ? NodeType.Folder : NodeType.File)),
        //                                ////DType = m.Difficulty == null ? DifficultyType.Difficult : (m.Difficulty == 1 ? DifficultyType.Easy : (m.Difficulty == 2 ? DifficultyType.Medium : DifficultyType.Difficult)),
        //                                //Width = m.Width,
        //                                //Height = m.Height,
        //                                //Left = m.Left,
        //                                //Top = m.Top,
        //                                //Layer = m.Layer,
        //                                ////EStatus = m.Flag == null ? EditStatus.Original : (m.Flag == 1 ? EditStatus.Original : EditStatus.Modified),
        //                                //Remark = m.Remark,
        //                                //OrderNo = m.OrderNo,
        //                                //ThemeID = m.ThemeID
        //                                #endregion

        //                                Element = m
        //                            };
        //                List<ElementNode> queryList = query.ToList();

        //                ElementNode tv = new ElementNode();

        //                result = queryList.Where(v => v.Element.ParentID == null).ToList();
        //                tv.Children.AddRange(result);
        //                foreach (var item in tv.Children)
        //                {
        //                    CreateSubTree(item, queryList);
        //                }
        //            }
        //            break;
        //    }
        //    return result;
        //}

        ///// <summary>
        ///// 创建子节点
        ///// </summary>
        ///// <param name="root"></param>
        ///// <param name="list"></param>
        //private void CreateSubTree(ElementNode root, List<ElementNode> list)
        //{
        //    foreach (var item in list)
        //    {
        //        if (item.Element.ParentID == root.Element.ID)
        //        {
        //            root.Children.Add(item);
        //            CreateSubTree(item, list);  //递归子节点
        //        }
        //    }
        //}
        //#endregion

        ///// <summary>
        ///// 新增元素
        ///// </summary>
        ///// <param name="data"></param>
        ///// <param name="dbType"></param>
        //public void AddElement(BF_Element data, DBType dbType)
        //{
        //    switch (dbType)
        //    {
        //        case DBType.MsSql: break;
        //        case DBType.SqlCompact:
        //            using (DBEntities dbContext = new DBEntities())
        //            {
        //                if (data.ID == Guid.Empty)
        //                {
        //                    data.ID = Guid.NewGuid();
        //                    dbContext.BF_Element.AddObject(data);
        //                }
        //                else
        //                {
        //                    dbContext.BF_Element.Attach(data);
        //                    dbContext.ObjectStateManager.ChangeObjectState(data, System.Data.EntityState.Modified);
        //                }
        //                dbContext.SaveChanges();
        //            }
        //            break;
        //        default: break;
        //    }
        //}

        ///// <summary>
        ///// 获取节点完整路径（依次向上找出父节点，整合）
        ///// </summary>
        ///// <param name="node">节点</param>
        ///// <param name="dbType">数据库类型</param>
        ///// <returns></returns>
        //public string GetFullPath(ElementNode node, DBType dbType)
        //{
        //    string result = string.Empty;

        //    List<string> names = new List<string>();
        //    names.Add(node.Element.Name);

        //    switch (dbType)
        //    {
        //        case DBType.MsSql: break;
        //        case DBType.SqlCompact:
        //            using (DBEntities dbContext = new DBEntities())
        //            {
        //                //此处需循环
        //                FindParent(names, node.Element.ParentID, dbType);
        //            }
        //            break;
        //        default: break;
        //    }
        //    names.Reverse();
        //    result = Path.Combine(names.ToArray());
        //    return result;
        //}

        ///// <summary>
        ///// 依次查找父节点，并将节点名称添加到names
        ///// </summary>
        ///// <param name="names"></param>
        ///// <param name="parentID"></param>
        ///// <param name="dbType"></param>
        //public void FindParent(List<string> names, Guid? parentID, DBType dbType)
        //{
        //    switch (dbType)
        //    {
        //        case DBType.MsSql: break;
        //        case DBType.SqlCompact:
        //            using (DBEntities dbContext = new DBEntities())
        //            {
        //                //此处需循环
        //                var parent = dbContext.BF_Element.Where(v => v.ID == parentID).FirstOrDefault();
        //                if (parent != null)
        //                {
        //                    names.Add(parent.Name);
        //                    FindParent(names, parent.ID, dbType);
        //                }
        //            }
        //            break;
        //        default: break;
        //    }
        //}
        #endregion

        #region 新设计 2012-05-09
        #region ElementWin辅助
        /// <summary>
        /// 获取所有元素列表
        /// </summary>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public List<BF_Element> GetElementList(DBType dbType)
        {
            List<BF_Element> result = new List<BF_Element>();
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        var query = from m in dbContext.BF_Element
                                    select m;
                        result = query.ToList();
                    }
                    break;
                default: break;
            }
            return result;
        }

        /// <summary>
        /// 保存元素列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <param name="deletedList"></param>
        /// <param name="dbType"></param>
        public void SaveElementList(IList<BF_Element> dataList, IList<BF_Element> deletedList, DBType dbType)
        {
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        foreach (var item in dataList)
                        {
                            if (item.EntityState == System.Data.EntityState.Detached || item.EntityState == System.Data.EntityState.Added)
                            {
                                dbContext.BF_Element.AddObject(item);
                            }
                            else if (item.EntityState == System.Data.EntityState.Modified)
                            {
                                dbContext.BF_Element.Attach(item);
                                dbContext.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Modified);
                            }
                        }
                        foreach (var item in deletedList)
                        {
                            dbContext.BF_Element.DeleteObject(item);
                        }
                        dbContext.SaveChanges();
                    }
                    break;
                default: break;
            }
        }
        #endregion

        /// <summary>
        /// 获取父级预览图视图列表（预览视图）
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        public List<BF_Element> GetParentPreviewList(DBType dbType)
        {
            List<BF_Element> result = new List<BF_Element>();
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        var query = from m in dbContext.BF_Element
                                    where m.ParentID == null
                                    select m;
                        result = query.ToList();
                    }
                    break;
                default: break;
            }
            return result;
        }

        /// <summary>
        /// 获取子级预览图视图列表（预览视图）
        /// </summary>
        /// <param name="parentID">父级ID</param>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        public List<BF_Element> GetChildPreviiewList(Guid parentID, DBType dbType)
        {
            List<BF_Element> result = new List<BF_Element>();
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        var query = from m in dbContext.BF_Element
                                    where m.ParentID == parentID
                                    select m;
                        result = query.ToList();
                    }
                    break;
                default: break;
            }
            return result;
        }

        /// <summary>
        /// 获取文件夹树表（预览视图/文件夹视图）
        /// </summary>
        /// <param name="previewID">预览图ID（为空时表示文件夹视图的树）</param>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        public List<ElementNode> GetFolderList(Guid? previewID, DBType dbType)
        {
            List<ElementNode> result = new List<ElementNode>();
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        var query = from m in dbContext.BF_Element
                                    orderby m.ParentID, m.OrderNo
                                    select new ElementNode
                                    {
                                        Element = m
                                    };
                        List<ElementNode> queryList = query.ToList();
                        ElementNode tv = new ElementNode();  //树根节点
                        //预览图下的文件夹树构建
                        if (previewID != null)
                            result = queryList.Where(v => v.Element.ParentID == previewID).ToList();
                        //直接构建文件夹树
                        else
                        {
                            //条件：文件夹类型、父节点是预览图，那么它就是一级的文件夹节点
                            List<ElementNode> folderList = queryList.Where(v => v.Element.Type == 2).ToList();
                            List<ElementNode> previewList = queryList.Where(v => v.Element.Type == 1).ToList();
                            foreach (var item in folderList)
                            {
                                if (previewList.Where(v => v.Element.ID == item.Element.ParentID).Count() > 0)
                                {
                                    result.Add(item);
                                }
                            }
                        }
                        tv.Children.AddRange(result);
                        foreach (var item in tv.Children)
                        {
                            CreateSubNode(item, queryList);  //创建子节点
                        }
                    }
                    break;
                default: break;
            }
            return result;
        }

        /// <summary>
        /// 创建子节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="list"></param>
        private void CreateSubNode(ElementNode parentNode, List<ElementNode> list)
        {
            foreach (var item in list)
            {
                if (item.Element.ParentID == parentNode.Element.ID)
                {
                    parentNode.Children.Add(item);
                    CreateSubNode(item, list);  //递归子节点
                }
            }
        }

        /// <summary>
        /// 获取节点完整路径（依次向上找出父节点，整合）
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        public string GetFullPath(ElementNode node, DBType dbType)
        {
            string result = string.Empty;

            List<string> names = new List<string>();
            names.Add(node.Element.Name);

            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        //此处需循环（递归）
                        FindParent(names, node.Element.ParentID, dbType);
                    }
                    break;
                default: break;
            }
            names.Reverse();
            result = Path.Combine(names.ToArray());
            return result;
        }

        /// <summary>
        /// 依次查找父节点，并将节点名称添加到names
        /// </summary>
        /// <param name="names"></param>
        /// <param name="parentID"></param>
        /// <param name="dbType"></param>
        public void FindParent(List<string> names, Guid? parentID, DBType dbType)
        {
            switch (dbType)
            {
                case DBType.MsSql: break;
                case DBType.SqlCompact:
                    using (DBEntities dbContext = new DBEntities())
                    {
                        //此处需循环（递归）
                        var parent = dbContext.BF_Element.Where(v => v.ID == parentID && v.Type == 2).FirstOrDefault();
                        if (parent != null)
                        {
                            names.Add(parent.Name);
                            FindParent(names, parent.ID, dbType);
                        }
                    }
                    break;
                default: break;
            }
        }
        #endregion
    }

    /// <summary>
    /// 元素节点实体
    /// </summary>
    public class ElementNode
    {
        /// <summary>
        /// 元素
        /// </summary>
        public BF_Element Element { get; set; }

        /// <summary>
        /// 子节点
        /// </summary>
        private List<ElementNode> children;
        public List<ElementNode> Children
        {
            get
            {
                if (children == null)
                    children = new List<ElementNode>();
                return children;
            }
            set
            {
                if (children == null)
                    children = new List<ElementNode>();
                children = value;
            }
        }

        /// <summary>
        /// 是否可见
        /// </summary>
        public bool IsVisible { get; set; }

        #region 原设计
        ///// <summary>
        ///// ID
        ///// </summary>
        //public Guid ID { get; set; }
        ///// <summary>
        ///// 节点名称
        ///// </summary>
        //public string Name { get; set; }
        ///// <summary>
        ///// 难度系数
        ///// </summary>
        //public DifficultyType DType { get; set; }
        ///// <summary>
        ///// 子节点
        ///// </summary>
        //private List<ElementNode> children;
        //public List<ElementNode> Children
        //{
        //    get
        //    {
        //        if (children == null)
        //            children = new List<ElementNode>();
        //        return children;
        //    }
        //    set
        //    {
        //        if (children == null)
        //            children = new List<ElementNode>();
        //        children = value;
        //    }
        //}
        ///// <summary>
        ///// 编辑状态
        ///// </summary>
        //public EditStatus EStatus { get; set; }
        ///// <summary>
        ///// 根节点
        ///// </summary>
        //public ElementNode RootNode { get; set; }
        ///// <summary>
        ///// 父节点
        ///// </summary>
        //public ElementNode ParentNode { get; set; }
        ///// <summary>
        ///// 父ID（有上面的父节点，父ID可以省略）
        ///// </summary>
        //public Guid? ParentID { get; set; }
        ///// <summary>
        ///// 路径
        ///// </summary>
        //public string Path { get; set; }
        ///// <summary>
        ///// 宽
        ///// </summary>
        //public decimal? Width { get; set; }
        ///// <summary>
        ///// 高
        ///// </summary>
        //public decimal? Height { get; set; }
        ///// <summary>
        ///// X坐标
        ///// </summary>
        //public decimal? Left { get; set; }
        ///// <summary>
        ///// Y坐标
        ///// </summary>
        //public decimal? Top { get; set; }
        ///// <summary>
        ///// 层
        ///// </summary>
        //public int? Layer { get; set; }
        ///// <summary>
        ///// 节点类型（元数据类型、元数据）
        ///// </summary>
        //public NodeType NType { get; set; }
        ///// <summary>
        ///// 备注
        ///// </summary>
        //public string Remark { get; set; }
        ///// <summary>
        ///// 排序
        ///// </summary>
        //public int? OrderNo { get; set; }
        ///// <summary>
        ///// 主题ID
        ///// </summary>
        //public Guid? ThemeID { get; set; }
        #endregion
    }
}
